import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/match/list/match_page_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

import '../../widgets/base/GradientIndicator.dart';

class MatchPage extends StatefulWidget {
  const MatchPage({super.key});

  @override
  State<MatchPage> createState() => _MatchPageState();
}

class _MatchPageState extends State<MatchPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  final logic = Get.put(MatchPageLogic(), permanent: true);
  late final TabController tabC = TabController(length: 2, vsync: this);

  bool visible = false;

  @override
  void initState() {
    super.initState();
    tabC.addListener(() {
      logic.headIndex = tabC.index;
      update();
    });
    Timer.periodic(const Duration(seconds: 10), (timer) {
      if (!visible) {
        return;
      }
      logic.getMatchController().getMatch();
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<MatchPageLogic>(
      builder: (MatchPageLogic logic) => Scaffold(
          backgroundColor: Colours.greyF2F3F7,
          body: VisibilityDetector(
              onVisibilityChanged: (info) {
                visible = !info.visibleBounds.isEmpty;
              },
              key: const Key("match key"),
              child: LoadingWidget<bool>(
                reconnect: logic.getRefresh,
                isLoading: logic.isLoading,
                loading: Container(),
                data: false,
                child: () => Stack(alignment: Alignment.topCenter, children: [
                  Image.asset(Utils.getImgPath("nav_head_back.png"),
                      width: Get.width, height: Get.width * 128 / 375),
                  Column(children: [
                    AppBar(
                        backgroundColor: Colours.transparent,
                        title: Styles.tabbar(
                          tabs: [
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 20), // 增加左右间距
                              child: Tab(
                                child: Image.asset(
                                  logic.headIndex == 0
                                      ? Utils.getImgPath("rm_choose.png")
                                      : Utils.getImgPath("rm_unchoose.png"),
                                  width: 40,
                                  height: 22,
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 20), // 增加左右间距
                              child: Tab(
                                child: Image.asset(
                                    logic.headIndex == 1
                                        ? Utils.getImgPath("zq_choose.png")
                                        : Utils.getImgPath("zq_unchoose.png"),
                                    width: 40,
                                    height: 22),
                              ),
                            )
                          ],
                          controller: tabC,
                          scrollable: true,
                          labelPadding: EdgeInsets.zero,
                          // indicatorPadding: EdgeInsets.only(top: 40.0),
                          indicatorBottom: 6,
                          labelColor: Colours.white,
                          indicator: GradientIndicator(
                            // tabController: tabC,
                            indicatorBottom: 6,
                            indicatorWidth: 18,
                            indicatorHeight: 4,
                            gradientColors: [
                              Colours.indicatorStart,
                              Colours.indicatorEnd,
                            ],
                          ),
                          unselectedLabelColor: Colours.white,
                          onTap: (value) {
                            Utils.onEvent('match_tab', params: {'tab': value});
                          },
                        ),
                        leading: Opacity(
                            opacity: logic.opacity,
                            child: Row(children: [
                              IconButton(
                                  onPressed: goFilter,
                                  icon: Image.asset(
                                    Utils.getImgPath('icon_screen.png'),
                                    width: 18,
                                    height: 18,
                                    color: Colours.text,
                                  )),
                              IconButton(
                                  onPressed: goSetting,
                                  icon: Image.asset(
                                    Utils.getImgPath('icon_score.png'),
                                    width: 18,
                                    height: 18,
                                    color: Colours.text,
                                  ))
                            ])),
                        actions: [
                          Opacity(
                              opacity: logic.opacity,
                              child: Row(children: [
                                IconButton(
                                    onPressed: goSetting,
                                    icon: Image.asset(
                                      Utils.getImgPath('icon_settings.png'),
                                      width: 18,
                                      height: 18,
                                      color: Colours.text,
                                    )),
                                IconButton(
                                    onPressed: goSetting,
                                    icon: Image.asset(
                                      Utils.getImgPath('icon_live.png'),
                                      width: 18,
                                      height: 18,
                                      color: Colours.text,
                                    ))
                              ]))
                        ]),
                    Expanded(
                        child: TabBarView(
                      physics: const ClampingScrollPhysics(),
                      controller: tabC,
                      children: List.generate(2, (index) => body(index)),
                    ))
                  ])
                ]),
              ))),
    );
  }

  Widget body(int index) {
    return GetBuilder<MatchPageLogic>(builder: (logic) {
      return LoadingWidget<bool>(
        isLoading: logic.isLoading,
        loading: Container(),
        data: false,
        child: () => Column(
          children: [
            SizedBox(
              height: 40,
              child: Styles.tabbar(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  physics: const ClampingScrollPhysics(),
                  tabs: (index == 1 ? logic.zqTabs : logic.lqTabs).map((f) {
                    return f.contains("http")
                        ? CachedNetworkImage(
                            imageUrl: f, height: 29, fit: BoxFit.fitWidth)
                        : QsText(f);
                  }).toList(),
                  labelPadding: EdgeInsets.zero,
                  controller: index == 1 ? logic.zqC : logic.lqC,
                  onTap: (value) {
                    Utils.onEvent('match_channel', params: {
                      'channel':
                          index == 1 ? logic.zqTabs[index] : logic.lqTabs[index]
                    });
                    logic.changeTab(value);
                  },
                  fontSize: 16),
            ),
            Expanded(
              child: MediaQuery.removePadding(
                context: context,
                removeTop: true,
                child: Container(
                  color: Colours.greyF2F3F7,
                  child: TabBarView(
                    controller: index == 1 ? logic.zqC : logic.lqC,
                    children: index == 1
                        ? List.generate(logic.zqTabs.length,
                            (index) => logic.zqPages[index])
                        : List.generate(logic.lqTabs.length,
                            (index) => logic.lqPages[index]),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  goSetting() {
    Utils.onEvent('match_setting');
    if (logic.headIndex == 1) {
      Get.toNamed(Routes.zqConfig);
    } else {
      Get.toNamed(Routes.lqConfig);
    }
  }

  goFilter() {
    Utils.onEvent('match_filter');
    if (logic.headIndex == 1) {
      Get.toNamed(Routes.zqFilter, arguments: logic.zqTags[logic.soccerIndex]);
    } else {
      Get.toNamed(Routes.basketballFilter,
          arguments: logic.lqTags[logic.basketIndex]);
    }
  }

  @override
  bool get wantKeepAlive => true;
}
